package com.hiflying.smartlink;

import android.content.Context;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Base64;

import com.hiflying.commons.log.HFLog;
import com.hiflying.commons.utils.ByteTool;
import com.hiflying.commons.utils.CrcCalculator;
import com.hiflying.commons.utils.GAES;
import com.hiflying.commons.utils.SmartLinkUtils;

import org.java_websocket.drafts.Draft_75;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Method;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;

public abstract class AbstractSmartLinker implements ISmartLinker {
    private static final String HF_A11ASSISTHREAD = "HF-A11ASSISTHREAD";
    @Deprecated
    public static int MAX_DURATION_RECEIVE_SMART_CONFIG = ISmartLinker.DEFAULT_TIMEOUT_PERIOD;
    @Deprecated
    public static int MAX_DURATION_WAIT_MORE_DEVICE = 10000;
    private static final int MSG_SMART_LINK_COMPLETED = 2;
    private static final int MSG_SMART_LINK_NEW_DEVICE = 1;
    private static final int PORT_RECEIVE_AIRKISS_REPORT = 10000;
    public static int PORT_RECEIVE_SMART_CONFIG = 49999;
    public static int PORT_SEND_SMART_LINK_FIND = 48899;
    public static String SMART_CONFIG = "smart_config";
    public static String SMART_LINK_FIND = "smartlinkfind";
    private long findDeivceTime = Long.MAX_VALUE;
    private Map<String, DatagramSocket> mA11AssisThreadSockets = new HashMap();
    protected Context mContext;
    private HashSet<String> mDeviceMacs = new HashSet<>();
    private Handler mHander = new Handler() {
        /* class com.hiflying.smartlink.AbstractSmartLinker.AnonymousClass1 */

        @Override // android.os.Handler
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (AbstractSmartLinker.this.mOnSmartLinkListener != null) {
                        AbstractSmartLinker.this.mOnSmartLinkListener.onLinked((SmartLinkedModule) msg.obj);
                        return;
                    }
                    return;
                case 2:
                    if (AbstractSmartLinker.this.mOnSmartLinkListener == null) {
                        return;
                    }
                    if (AbstractSmartLinker.this.mDeviceMacs.isEmpty()) {
                        AbstractSmartLinker.this.mOnSmartLinkListener.onTimeOut();
                        return;
                    } else {
                        AbstractSmartLinker.this.mOnSmartLinkListener.onCompleted();
                        return;
                    }
                default:
                    return;
            }
        }
    };
    protected boolean mIsSmartLinking;
    protected boolean mIsTimeout;
    protected OnSmartLinkListener mOnSmartLinkListener;
    private String mOthers;
    private boolean mReceiveAirkissReportEnabled = true;
    private DatagramSocket mReceiveAirkissReportSocket;
    private boolean mReceiveSmartConfigEnabled = true;
    private boolean mSendSmartLinkFindEnabled = true;
    protected MulticastSocket mSmartConfigSocket;
    protected int mTimeoutPeriod = ISmartLinker.DEFAULT_TIMEOUT_PERIOD;
    private int mWaitMoreDevicePeriod = MAX_DURATION_WAIT_MORE_DEVICE;

    /* access modifiers changed from: protected */
    public abstract Runnable[] setupSendAction(String str, String str2) throws Exception;

    public boolean isSendSmartLinkFindEnabled() {
        return this.mSendSmartLinkFindEnabled;
    }

    public void setSendSmartLinkFindEnabled(boolean sendSmartLinkFindEnabled) {
        this.mSendSmartLinkFindEnabled = sendSmartLinkFindEnabled;
    }

    public boolean isReceiveSmartConfigEnabled() {
        return this.mReceiveSmartConfigEnabled;
    }

    public void setReceiveSmartConfigEnabled(boolean receiveSmartConfigEnabled) {
        this.mReceiveSmartConfigEnabled = receiveSmartConfigEnabled;
    }

    protected AbstractSmartLinker() {
    }

    public void initSmartConfigSocket() throws Exception {
        this.mSmartConfigSocket = new MulticastSocket(PORT_RECEIVE_SMART_CONFIG);
        this.mSmartConfigSocket.joinGroup(InetAddress.getByName("239.0.0.0"));
        this.mSmartConfigSocket.setLoopbackMode(false);
        this.mSmartConfigSocket.setSoTimeout(1200);
    }

    public void closeDestroySmartConfigSocket() {
        if (this.mSmartConfigSocket != null) {
            this.mSmartConfigSocket.close();
            this.mSmartConfigSocket.disconnect();
            this.mSmartConfigSocket = null;
        }
    }

    private void initReceiveAirkissReportSocket() throws Exception {
        this.mReceiveAirkissReportSocket = new DatagramSocket(10000);
        this.mReceiveAirkissReportSocket.setSoTimeout(1200);
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private void closeDestroyReceiveAirkissReportSocket() {
        if (this.mReceiveAirkissReportSocket != null) {
            this.mReceiveAirkissReportSocket.close();
            this.mReceiveAirkissReportSocket.disconnect();
            this.mReceiveAirkissReportSocket = null;
        }
        closeDestroyA11AssisThreadSocket();
    }

    private void closeDestroyA11AssisThreadSocket() {
        for (DatagramSocket datagramSocket : this.mA11AssisThreadSockets.values()) {
            if (datagramSocket != null) {
                datagramSocket.close();
                datagramSocket.disconnect();
            }
        }
        this.mA11AssisThreadSockets.clear();
    }

    public DatagramSocket getSmartConfigSocket() {
        return this.mSmartConfigSocket;
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private Runnable[] createSenderRunnables(final CountDownLatch latch, final Runnable[] runnables) {
        Runnable[] _runnnables = null;
        if (runnables != null) {
            _runnnables = new Runnable[runnables.length];
            for ( int i = 0; i < runnables.length; i++) {
                final int mI = i;

                _runnnables[i] = new Runnable() {
                    /* class com.hiflying.smartlink.AbstractSmartLinker.AnonymousClass2 */

                    @Override // java.lang.Runnable
                    public void run() {
                        runnables[mI].run();
                        latch.countDown();
                    }
                };
            }
        }
        return _runnnables;
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private Runnable createReceiverRunnable(final CountDownLatch latch) {
        return new Runnable() {
            /* class com.hiflying.smartlink.AbstractSmartLinker.AnonymousClass3 */

            @Override // java.lang.Runnable
            public void run() {
                AbstractSmartLinker.this.setupReceiveAction().run();
                latch.countDown();
            }
        };
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private Runnable createAirkissReportReceiverRunnable(final CountDownLatch latch) {
        return new Runnable() {
            /* class com.hiflying.smartlink.AbstractSmartLinker.AnonymousClass4 */

            @Override // java.lang.Runnable
            public void run() {
                AbstractSmartLinker.this.setupReceiveAirkissReportAction().run();
                latch.countDown();
            }
        };
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private Runnable createSmartLinkFindRunnable(final CountDownLatch latch) {
        return new Runnable() {
            /* class com.hiflying.smartlink.AbstractSmartLinker.AnonymousClass5 */

            @Override // java.lang.Runnable
            public void run() {
                AbstractSmartLinker.this.setupSmartLinkFindAction().run();
                latch.countDown();
            }
        };
    }

    /* access modifiers changed from: protected */
    public Runnable setupReceiveAction() {
        return new Runnable() {
            /* class com.hiflying.smartlink.AbstractSmartLinker.AnonymousClass6 */

            @Override // java.lang.Runnable
            public void run() {
                AbstractSmartLinker.this.mDeviceMacs.clear();
                byte[] buffer = new byte[1024];
                DatagramPacket pack = new DatagramPacket(buffer, buffer.length);
                long startTime = System.currentTimeMillis();
                while (AbstractSmartLinker.this.mIsSmartLinking) {
                    long currentTime = System.currentTimeMillis();
                    if (!AbstractSmartLinker.this.mIsSmartLinking || currentTime - startTime > ((long) AbstractSmartLinker.this.mTimeoutPeriod) || currentTime - AbstractSmartLinker.this.findDeivceTime > ((long) AbstractSmartLinker.this.mWaitMoreDevicePeriod)) {
                        break;
                    }
                    try {
                        AbstractSmartLinker.this.mSmartConfigSocket.receive(pack);
                        byte[] datas = new byte[pack.getLength()];
                        System.arraycopy(buffer, 0, datas, 0, datas.length);
                        if (datas.length >= 25) {
                            boolean ignore = true;
                            for (int i = 0; i < datas.length; i++) {
                                ignore = datas[i] == 5;
                                if (!ignore) {
                                    break;
                                }
                            }
                            if (!ignore) {
                                StringBuffer sb = new StringBuffer();
                                for (byte b : datas) {
                                    sb.append((char) b);
                                }
                                String result = sb.toString().trim();
                                String mac = null;
                                String ip = null;
                                String id = null;
                                if (result.startsWith(AbstractSmartLinker.SMART_CONFIG)) {
                                    HFLog.d(AbstractSmartLinker.this, "Received: " + result);
                                    String[] items = result.replace(AbstractSmartLinker.SMART_CONFIG, "").trim().split("##");
                                    if (items.length > 0) {
                                        mac = items[0].trim();
                                        if (items.length <= 1 || TextUtils.isEmpty(items[1].trim())) {
                                            id = mac;
                                        } else {
                                            id = items[1].trim();
                                        }
                                    }
                                } else {
                                    try {
                                        JSONObject jsonObject = new JSONObject(result);
                                        id = jsonObject.optString("mid");
                                        mac = jsonObject.optString("mac");
                                        ip = jsonObject.optString("ip");
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                                if (!TextUtils.isEmpty(mac) && !AbstractSmartLinker.this.mDeviceMacs.contains(mac)) {
                                    if (TextUtils.isEmpty(id) || id.trim().isEmpty()) {
                                        id = mac;
                                    }
                                    if (TextUtils.isEmpty(ip)) {
                                        ip = pack.getAddress().getHostAddress();
                                    }
                                    SmartLinkedModule module = new SmartLinkedModule();
                                    module.setId(id);
                                    module.setMac(mac);
                                    module.setIp(ip);
                                    AbstractSmartLinker.this.mDeviceMacs.add(mac);
                                    AbstractSmartLinker.this.mHander.sendMessage(AbstractSmartLinker.this.mHander.obtainMessage(1, module));
                                    if (AbstractSmartLinker.this.findDeivceTime == Long.MAX_VALUE) {
                                        AbstractSmartLinker.this.findDeivceTime = System.currentTimeMillis();
                                    }
                                }
                            }
                        }
                    } catch (IOException e2) {
                        HFLog.v(AbstractSmartLinker.this, "smartLinkSocket.receive(pack) timeout");
                    }
                }
                AbstractSmartLinker.this.mIsSmartLinking = false;
            }
        };
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private Runnable setupReceiveAirkissReportAction() {
        return new Runnable() {
            /* class com.hiflying.smartlink.AbstractSmartLinker.AnonymousClass7 */

            @Override // java.lang.Runnable
            public void run() {
                HFLog.d(AbstractSmartLinker.this, "ReceiveAirkissReportAction started");
                AbstractSmartLinker.this.mA11AssisThreadSockets.clear();
                byte[] buffer = new byte[16];
                DatagramPacket pack = new DatagramPacket(buffer, buffer.length);
                while (AbstractSmartLinker.this.mIsSmartLinking) {
                    try {
                        AbstractSmartLinker.this.mReceiveAirkissReportSocket.receive(pack);
                        byte[] datas = new byte[pack.getLength()];
                        System.arraycopy(buffer, 0, datas, 0, datas.length);
                        InetAddress deviceAddress = pack.getAddress();
                        int data_0 = datas[0] & Draft_75.END_OF_FRAME;
                        if (datas.length == 1 && ((data_0 == 0 || data_0 == 170) && !AbstractSmartLinker.this.mA11AssisThreadSockets.containsKey(deviceAddress.getHostAddress()))) {
                            try {
                                AbstractSmartLinker.this.mA11AssisThreadSockets.put(deviceAddress.getHostAddress(), AbstractSmartLinker.this.createA11AssisThread(pack.getAddress()));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    } catch (IOException e2) {
                        HFLog.v(AbstractSmartLinker.this, "mReceiveAirkissReportSocket.receive(pack) timeout");
                    }
                }
                HFLog.d(AbstractSmartLinker.this, "ReceiveAirkissReportAction finished");
            }
        };
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private DatagramSocket createA11AssisThread(final InetAddress deviceAddress) throws Exception {
        final DatagramSocket socket = new DatagramSocket();
        socket.setSoTimeout(1200);
        byte[] sendingData = HF_A11ASSISTHREAD.getBytes();
        final DatagramPacket sendingPacket = new DatagramPacket(sendingData, sendingData.length, new InetSocketAddress(deviceAddress, PORT_SEND_SMART_LINK_FIND));
        final byte[] receivingData = new byte[256];
        final DatagramPacket receivingPacket = new DatagramPacket(receivingData, receivingData.length);
        new Thread(new Runnable() {
            /* class com.hiflying.smartlink.AbstractSmartLinker.AnonymousClass8 */

            @Override // java.lang.Runnable
            public void run() {
                String id;
                HFLog.d(AbstractSmartLinker.this, String.valueOf(deviceAddress.getHostName()) + " A11AssisThread started");
                while (AbstractSmartLinker.this.mIsSmartLinking) {
                    HFLog.v(AbstractSmartLinker.this, "A11AssisThread sending");
                    try {
                        socket.send(sendingPacket);
                    } catch (IOException e) {
                        HFLog.v(AbstractSmartLinker.this, "A11AssisThread send failed");
                    }
                    try {
                        socket.receive(receivingPacket);
                        byte[] datas = new byte[receivingPacket.getLength()];
                        System.arraycopy(receivingData, 0, datas, 0, datas.length);
                        if (datas.length > 19) {
                            String text = new String(datas);
                            HFLog.d(AbstractSmartLinker.class.getName(), "Receive message: " + text);
                            String[] items = text.split(",");
                            if (items.length > 1) {
                                String ip = items[0];
                                String mac = items[1];
                                if (items.length > 2) {
                                    id = items[2];
                                } else {
                                    id = mac;
                                }
                                if (!TextUtils.isEmpty(mac) && !AbstractSmartLinker.this.mDeviceMacs.contains(mac)) {
                                    if (TextUtils.isEmpty(id) || id.trim().isEmpty()) {
                                        id = mac;
                                    }
                                    if (TextUtils.isEmpty(ip)) {
                                        ip = receivingPacket.getAddress().getHostAddress();
                                    }
                                    SmartLinkedModule module = new SmartLinkedModule();
                                    module.setId(id);
                                    module.setMac(mac);
                                    module.setIp(ip);
                                    AbstractSmartLinker.this.mDeviceMacs.add(mac);
                                    AbstractSmartLinker.this.mHander.sendMessage(AbstractSmartLinker.this.mHander.obtainMessage(1, module));
                                    if (AbstractSmartLinker.this.findDeivceTime == Long.MAX_VALUE) {
                                        AbstractSmartLinker.this.findDeivceTime = System.currentTimeMillis();
                                    }
                                }
                            }
                        }
                    } catch (IOException e2) {
                        HFLog.v(AbstractSmartLinker.this, "A11AssisThread receive timeout");
                    }
                }
                socket.close();
                socket.disconnect();
                HFLog.d(AbstractSmartLinker.this, String.valueOf(deviceAddress.getHostName()) + " A11AssisThread finished");
            }
        }).start();
        return socket;
    }

    /* access modifiers changed from: protected */
    public Runnable setupSmartLinkFindAction() {
        return new Runnable() {
            /* class com.hiflying.smartlink.AbstractSmartLinker.AnonymousClass9 */

            @Override // java.lang.Runnable
            public void run() {
                byte[] data = AbstractSmartLinker.SMART_LINK_FIND.getBytes();
                InetAddress broadcastIpAddress = null;
                while (AbstractSmartLinker.this.mIsSmartLinking) {
                    if (broadcastIpAddress == null) {
                        try {
                            broadcastIpAddress = InetAddress.getByName(SmartLinkUtils.getBroadcastAddress(AbstractSmartLinker.this.mContext));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    try {
                        AbstractSmartLinker.this.mSmartConfigSocket.send(new DatagramPacket(data, data.length, broadcastIpAddress, AbstractSmartLinker.PORT_SEND_SMART_LINK_FIND));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    AbstractSmartLinker.this.sleep(1000);
                }
            }
        };
    }

    @Override // com.hiflying.smartlink.ISmartLinker
    public void setOnSmartLinkListener(OnSmartLinkListener listener) {
        this.mOnSmartLinkListener = listener;
    }

    @Override // com.hiflying.smartlink.ISmartLinker
    public void start(Context context, final String password, final String ssid) throws Exception {
        if (this.mIsSmartLinking) {
            HFLog.w(this, "SmartLink is already linking, do not start it again!");
            return;
        }
        HFLog.d(this, "Smart Link started!");
        this.mIsSmartLinking = true;
        this.mContext = context;
        initSmartConfigSocket();
        if (this.mReceiveAirkissReportEnabled) {
            initReceiveAirkissReportSocket();
        }
        this.findDeivceTime = Long.MAX_VALUE;
        new Thread(new Runnable() {
            /* class com.hiflying.smartlink.AbstractSmartLinker.AnonymousClass10 */

            @Override // java.lang.Runnable
            public void run() {
                Runnable[] senderRunnables;
                Runnable[] senderActions = null;
                try {
                    senderActions = AbstractSmartLinker.this.setupSendAction(password, ssid);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
                int length = 0;
                if (AbstractSmartLinker.this.mSendSmartLinkFindEnabled) {
                    length = 0 + 1;
                }
                if (AbstractSmartLinker.this.mReceiveSmartConfigEnabled) {
                    length++;
                }
                if (AbstractSmartLinker.this.mReceiveAirkissReportEnabled) {
                    length++;
                }
                if (senderActions != null) {
                    length += senderActions.length;
                }
                CountDownLatch latch = new CountDownLatch(length);
                ExecutorService threadPool = Executors.newFixedThreadPool(length);
                AbstractSmartLinker.this.mIsTimeout = false;
                if (!(senderActions == null || (senderRunnables = AbstractSmartLinker.this.createSenderRunnables(latch, senderActions)) == null)) {
                    for (Runnable runnable : senderRunnables) {
                        threadPool.execute(runnable);
                    }
                }
                if (AbstractSmartLinker.this.mSendSmartLinkFindEnabled) {
                    threadPool.execute(AbstractSmartLinker.this.createSmartLinkFindRunnable(latch));
                }
                if (AbstractSmartLinker.this.mReceiveSmartConfigEnabled) {
                    threadPool.execute(AbstractSmartLinker.this.createReceiverRunnable(latch));
                }
                if (AbstractSmartLinker.this.mReceiveAirkissReportEnabled) {
                    threadPool.execute(AbstractSmartLinker.this.createAirkissReportReceiverRunnable(latch));
                }
                try {
                    AbstractSmartLinker.this.mIsTimeout = !latch.await((long) AbstractSmartLinker.this.mTimeoutPeriod, TimeUnit.MILLISECONDS);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                AbstractSmartLinker.this.mIsSmartLinking = false;
                threadPool.shutdownNow();
                AbstractSmartLinker.this.closeDestroySmartConfigSocket();
                AbstractSmartLinker.this.closeDestroyReceiveAirkissReportSocket();
                AbstractSmartLinker.this.mHander.sendEmptyMessage(2);
                HFLog.d(AbstractSmartLinker.this, "Smart Link finished!");
            }
        }).start();
        discoverWifiP2p(ssid, password, this.mOthers);
    }

    @Override // com.hiflying.smartlink.ISmartLinker
    public void stop() {
        this.mIsSmartLinking = false;
        closeDestroySmartConfigSocket();
    }

    @Override // com.hiflying.smartlink.ISmartLinker
    public boolean isSmartLinking() {
        return this.mIsSmartLinking;
    }

    @Override // com.hiflying.smartlink.ISmartLinker
    public void setTimeoutPeriod(int timeoutPeriod) {
        if (timeoutPeriod > 0) {
            this.mTimeoutPeriod = timeoutPeriod;
        }
    }

    @Override // com.hiflying.smartlink.ISmartLinker
    public void setOthers(String others) {
        this.mOthers = others;
    }

    public String getOthers() {
        return this.mOthers;
    }

    public void setWaitMoreDevicePeriod(int period) {
        this.mWaitMoreDevicePeriod = period;
    }

    private void discoverWifiP2p(final String ssid, final String password, final String otherInfo) {
        if (Build.VERSION.SDK_INT < 16) {
            HFLog.i(this, "The android version is lower than JELLY_BEAN(SDK16), it doesn't support wifi p2p discover");
        } else {
            new Thread(new Runnable() {
                /* class com.hiflying.smartlink.AbstractSmartLinker.AnonymousClass11 */

                @Override // java.lang.Runnable
                public void run() {
                    try {
                        AbstractSmartLinker.this._discoverWifiP2p(ssid, password, otherInfo);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

    /* access modifiers changed from: private */
    public class WifiP2pPeerDiscovery {
        private static final String AES_KEY = "smartlink-aeskey";
        private WifiP2pManager.Channel channel;
        private Context context;
        private boolean discoverSwitch = true;
        private boolean isAndroid8Min;
        private boolean once = true;
        private String otherInfo;
        private String password;
        private Method setDeviceNameMethod;
        private String ssid;
        final /* synthetic */ AbstractSmartLinker this$0;
        private WifiP2pManager wifiP2pManager;

        public WifiP2pPeerDiscovery(AbstractSmartLinker abstractSmartLinker, Context context2) {
            boolean z = true;
            this.this$0 = abstractSmartLinker;
            this.isAndroid8Min = Build.VERSION.SDK_INT < 26 ? false : z;
            this.context = context2;
        }

        public void init(String ssid2, String password2, String otherInfo2) throws Exception {
            this.ssid = ssid2;
            this.password = password2;
            this.otherInfo = otherInfo2;
            this.wifiP2pManager = (WifiP2pManager) this.context.getSystemService("wifip2p");
            this.channel = this.wifiP2pManager.initialize(this.context, this.context.getMainLooper(), null);
            this.setDeviceNameMethod = this.wifiP2pManager.getClass().getMethod("setDeviceName", WifiP2pManager.Channel.class, String.class, WifiP2pManager.ActionListener.class);
        }

        public void destroy() throws Exception {
            this.wifiP2pManager.stopPeerDiscovery(this.channel, null);
            this.once = true;
            this.discoverSwitch = true;
            this.ssid = null;
            this.password = null;
            this.otherInfo = null;
            this.context = null;
            this.wifiP2pManager = null;
            this.channel = null;
            this.setDeviceNameMethod = null;
        }

        public void switchDiscover() {
            boolean z;
            if (this.discoverSwitch) {
                z = false;
            } else {
                z = true;
            }
            this.discoverSwitch = z;
            this.once = true;
        }

        public void discover() {
            if ((!this.isAndroid8Min || !this.discoverSwitch) && (this.isAndroid8Min || this.discoverSwitch)) {
                onceDiscover();
            } else {
                alwaysDiscover();
            }
        }

        public List<String> getTextFrames() throws Exception {
            byte[] datas;
            String ssid2 = this.ssid;
            String password2 = this.password;
            String otherInfo2 = this.otherInfo;
            if (ssid2 == null) {
                ssid2 = "";
            }
            if (password2 == null) {
                password2 = "";
            }
            if (otherInfo2 == null) {
                otherInfo2 = "";
            }
            String wifiInfo = String.format("%s,%s,%s", ssid2.replaceAll(Matcher.quoteReplacement(","), Matcher.quoteReplacement("\\2c")), password2.replaceAll(Matcher.quoteReplacement(","), Matcher.quoteReplacement("\\2c")), otherInfo2.replaceAll(Matcher.quoteReplacement(","), Matcher.quoteReplacement("\\2c")));
            if (1 != 0) {
                datas = GAES.encrypt(wifiInfo.getBytes(), AES_KEY.getBytes());
            } else {
                datas = wifiInfo.getBytes();
            }
            byte[] datas2 = Base64.encode(datas, 2);
            String crc8Text = ByteTool.bytes2HexString(new byte[]{(byte) ((int) (new CrcCalculator(CrcCalculator.Crc8.Crc8Maxim).calc(datas2, 0, datas2.length) & 255))});
            int length = datas2.length;
            int dataCapacityPerFrame = 32 - 7;
            int frameCount = length / dataCapacityPerFrame;
            if (length % dataCapacityPerFrame != 0) {
                frameCount++;
            }
            List<String> textFrames = new ArrayList<>();
            int position = 0;
            for (int i = 1; i <= frameCount && this.this$0.mIsSmartLinking; i++) {
                int dataLengthInFrame = Math.min(length - position, dataCapacityPerFrame);
                byte[] frame = new byte[(7 + dataLengthInFrame)];
                frame[0] = 94;
                frame[1] = 96;
                frame[2] = (byte) (frame.length - 3);
                frame[3] = (byte) (frameCount & 255);
                frame[4] = (byte) (i & 255);
                frame[5] = (byte) crc8Text.charAt(0);
                frame[6] = (byte) crc8Text.charAt(1);
                System.arraycopy(datas2, position, frame, 7, dataLengthInFrame);
                position += dataLengthInFrame;
                textFrames.add(new String(frame));
            }
            return textFrames;
        }

        public void setDeviceName(final String deviceName) throws Exception {
            this.setDeviceNameMethod.invoke(this.wifiP2pManager, this.channel, deviceName, new WifiP2pManager.ActionListener() {
                /* class com.hiflying.smartlink.AbstractSmartLinker.WifiP2pPeerDiscovery.AnonymousClass1 */

                @Override // android.net.wifi.p2p.WifiP2pManager.ActionListener
                public void onSuccess() {
                    HFLog.d(WifiP2pPeerDiscovery.this.this$0, String.format("wifi p2p set device name success: data-%s, name-%s", ByteTool.byte2StringWithSpace(deviceName.getBytes()), deviceName));
                }

                @Override // android.net.wifi.p2p.WifiP2pManager.ActionListener
                public void onFailure(int reasonCode) {
                    HFLog.i(WifiP2pPeerDiscovery.this.this$0, String.format("wifi p2p set device name failure: data-%s, name-%s, reasonCode-%s", ByteTool.byte2StringWithSpace(deviceName.getBytes()), deviceName, Integer.valueOf(reasonCode)));
                }
            });
        }

        private void alwaysDiscover() {
            HFLog.i(this.this$0, "wifi p2p discover peers");
            this.this$0.sleep(50);
            this.wifiP2pManager.stopPeerDiscovery(this.channel, null);
            this.this$0.sleep(50);
            this.wifiP2pManager.discoverPeers(this.channel, null);
            this.this$0.sleep(400);
        }

        private void onceDiscover() {
            if (this.once) {
                HFLog.i(this.this$0, "wifi p2p discover peers once");
                this.this$0.sleep(50);
                this.wifiP2pManager.stopPeerDiscovery(this.channel, null);
                this.this$0.sleep(50);
                this.wifiP2pManager.discoverPeers(this.channel, null);
                this.once = false;
            }
            this.this$0.sleep(700);
        }
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private void _discoverWifiP2p(String ssid, String password, String otherInfo) throws Exception {
        WifiP2pPeerDiscovery wifiP2pPeerDiscovery = new WifiP2pPeerDiscovery(this, this.mContext);
        wifiP2pPeerDiscovery.init(ssid, password, otherInfo);
        List<String> textFrames = wifiP2pPeerDiscovery.getTextFrames();
        loop0:
        while (this.mIsSmartLinking) {
            for (int i = 0; i < 3; i++) {
                for (int j = 0; j < textFrames.size(); j++) {
                    wifiP2pPeerDiscovery.setDeviceName(textFrames.get(j));
                    wifiP2pPeerDiscovery.discover();
                    if (!this.mIsSmartLinking) {
                        break loop0;
                    }
                }
            }
            wifiP2pPeerDiscovery.switchDiscover();
        }
        wifiP2pPeerDiscovery.destroy();
    }

    /* access modifiers changed from: private */
    /* access modifiers changed from: public */
    private void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
